package china.accountinghelper.activity;

import com.xdroid.base.AsyncTaskBase;
import china.wc.tallyhelper.R;
import china.wc.tallyhelper.adapter.AdapterListViewBookList;
import china.wc.tallyhelper.business.BusinessBook;
import china.wc.tallyhelper.controls.SlideMenu;
import china.wc.tallyhelper.controls.SlideMenuItem;
import china.wc.tallyhelper.model.ModelBook;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;

public class ActivityBook extends ActivityFrame implements OnClickListener, OnItemClickListener
{
    public static final String             SELECTED_MODEL_OBJECT        = "ModelBook";
    public static final int                REQUEST_CODE_ADD_BOOK       = 1;
    public static final int                REQUEST_CODE_EDIT_BOOK      = 2;
    public static final int                RESULT_ERR                  = RESULT_FIRST_USER + 1;
    public static final int                DIALOG_CONFIRM_BOOK_DELETE  = 1;
    public static final int                DIALOG_CONFIRM_BOOK_DISABLE = 2;

    private ListView                mFramebodyBook_ListView_BookList;
    private AdapterListViewBookList mAdapterListViewBookList;
    private BusinessBook            mBusinessBook;
    // 当前正在操作的实体类对象
    private ModelBook               mSelectedModelBook;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // 载入主页面Layout文件
        loadFramebody(R.layout.framebody_book);
        // 生成主界面的SlideMenu菜单
        creatSlideMenu(R.array.slidemenu_book);
        // 设置标题
        setTopTitle(R.string.title_book);
        
        executeInitTask(null);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if (mAdapterListViewBookList!=null) {
            mAdapterListViewBookList.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        mAdapterListViewBookList.notifyDataSetChanged();

        if (requestCode == REQUEST_CODE_ADD_BOOK) {
            if (resultCode == RESULT_OK) {
                showToastShort(R.string.message_book_add_ok);
            } else if (resultCode == RESULT_ERR) {
                showToastShort(R.string.message_book_add_err);
            }

        } else if (requestCode == REQUEST_CODE_EDIT_BOOK) {
            if (resultCode == RESULT_OK) {
                showToastShort(getString(R.string.message_book_update_ok));
            } else if (resultCode == RESULT_ERR) {
                showToastShort(getString(R.string.message_book_update_err));
            }
        }
    }

    /**
     * 生成账本管理页面的上下文菜单，根据账本状态，动态改变菜单项。
     * 
     */
    @Override
    public void onCreateContextMenu(ContextMenu pMenu, View pView, ContextMenuInfo pMenuInfo)
    {
        AdapterView.AdapterContextMenuInfo _MenuInfo = (AdapterView.AdapterContextMenuInfo) pMenuInfo;
        mSelectedModelBook = mAdapterListViewBookList.getItem(_MenuInfo.position);

        inflateMenu(R.menu.contextmenu_booklist, pMenu);
        pMenu.setHeaderIcon(((ImageView)pView.findViewById(R.id.ItemListViewBookList_ImageView_Ico)).getDrawable())
                .setHeaderTitle(mSelectedModelBook.getName());

        if (mSelectedModelBook.getState() == ModelBook.STATE_ENABLED) {
            pMenu.findItem(R.id.ContextMenu_BookList_EditBook).setVisible(true).setEnabled(true);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateEnable).setVisible(false).setEnabled(false);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateDisable).setVisible(true).setEnabled(true);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateDefault).setVisible(true).setEnabled(true);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateEnableThenDefault).setVisible(false).setEnabled(false);
            pMenu.findItem(R.id.ContextMenu_BookList_DeleteBook).setVisible(true).setEnabled(true);
        } else if (mSelectedModelBook.getState() == ModelBook.STATE_DISABLED) {
            pMenu.findItem(R.id.ContextMenu_BookList_EditBook).setVisible(true).setEnabled(true);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateEnable).setVisible(true).setEnabled(true);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateDisable).setVisible(false).setEnabled(false);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateDefault).setVisible(false).setEnabled(false);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateEnableThenDefault).setVisible(true).setEnabled(true);
            pMenu.findItem(R.id.ContextMenu_BookList_DeleteBook).setVisible(true).setEnabled(true);
        } else if (mSelectedModelBook.getState() == ModelBook.STATE_DEFAULT) {
            pMenu.findItem(R.id.ContextMenu_BookList_EditBook).setVisible(true).setEnabled(true);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateEnable).setVisible(false).setEnabled(false);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateDisable).setVisible(true).setEnabled(true);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateDefault).setVisible(false).setEnabled(false);
            pMenu.findItem(R.id.ContextMenu_BookList_SetBookStateEnableThenDefault).setVisible(false).setEnabled(false);
            pMenu.findItem(R.id.ContextMenu_BookList_DeleteBook).setVisible(true).setEnabled(true);
        }
    }

    /**
     * 上下文菜单的点击事件
     */
    @Override
    public boolean onContextItemSelected(MenuItem item)
    {
        // 修改账本
        if (item.getItemId() == R.id.ContextMenu_BookList_EditBook) {
            Bundle _Bundle = new Bundle();
            _Bundle.putSerializable(SELECTED_MODEL_OBJECT, mSelectedModelBook);
            openActivityForResult(ActivityBookAddAndEdit.class, _Bundle, REQUEST_CODE_EDIT_BOOK);
        
        // 启用账本
        } else if (item.getItemId() == R.id.ContextMenu_BookList_SetBookStateEnable) {
            mBusinessBook.enableBook(mSelectedModelBook);
        
        // 禁用账本
        } else if (item.getItemId() == R.id.ContextMenu_BookList_SetBookStateDisable) {
            showDialog(DIALOG_CONFIRM_BOOK_DISABLE, null);
            
        // 设置为默认账本 && 启动并设置为默认账本
        } else if (item.getItemId() == R.id.ContextMenu_BookList_SetBookStateDefault || item.getItemId() == R.id.ContextMenu_BookList_SetBookStateEnableThenDefault) {
            mBusinessBook.setDefaultBook(mSelectedModelBook);
            
        // 删除账本
        } else if (item.getItemId() == R.id.ContextMenu_BookList_DeleteBook) {
            showDialog(DIALOG_CONFIRM_BOOK_DELETE, null);
        }
        
        mAdapterListViewBookList.notifyDataSetChanged();

        return super.onContextItemSelected(item);
    }

    @Override
    protected Dialog onCreateDialog(int pDialogId, Bundle pArgs)
    {
        AlertDialog.Builder _AlertDialogBuilder = new AlertDialog.Builder(this);

        // 删除警告对话框
        if (pDialogId == DIALOG_CONFIRM_BOOK_DELETE) {
            _AlertDialogBuilder.setTitle(R.string.title_book_delete)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setMessage(getString(R.string.message_book_check_delete))
                    .setPositiveButton(R.string.ok, this)
                    .setNegativeButton(R.string.cancel, this);
        // 禁用警告对话框
        } else if (pDialogId == DIALOG_CONFIRM_BOOK_DISABLE) {
            _AlertDialogBuilder.setTitle(R.string.title_book_disable)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setMessage(getString(R.string.message_book_check_disable))
                    .setPositiveButton(R.string.ok, this)
                    .setNegativeButton(R.string.cancel, this);
        }

        return _AlertDialogBuilder.create();
    }

    /**
     * Dialog按钮的点击事件
     */
    @Override
    public void onClick(DialogInterface dialog, int which)
    {
        // 删除警告对话框
        if (getShowingDialogID() == DIALOG_CONFIRM_BOOK_DELETE) {
            // 确定按钮
            if (which == DialogInterface.BUTTON_POSITIVE) {
                mBusinessBook.deleteModel(mSelectedModelBook);
            // 取消按钮
            } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                dialog.cancel();
            }
    
        // 禁用警告对话框
        } else if (getShowingDialogID() == DIALOG_CONFIRM_BOOK_DISABLE) {
            // 确定按钮
            if (which == DialogInterface.BUTTON_POSITIVE) {
                mBusinessBook.disableBook(mSelectedModelBook);
            // 取消按钮
            } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                dialog.cancel();
            }
        }
        
        mAdapterListViewBookList.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        mSelectedModelBook = mAdapterListViewBookList.getItem(position);
        Bundle _Bundle = new Bundle();
        _Bundle.putSerializable(SELECTED_MODEL_OBJECT, mSelectedModelBook);
        openActivity(ActivityBookDetail.class, _Bundle);
    }

    /**
     * SlideMenu的点击事件
     */
    @Override
    public void onSlideMenuItemClick(SlideMenu pSlideMenu, SlideMenuItem pSlideMenuItem, AdapterView<?> pParent, View pView, int pPosition, long pId)
    {
        if (pPosition == 0) {
            slideMenuToggle();
            openActivityForResult(ActivityBookAddAndEdit.class, null, REQUEST_CODE_ADD_BOOK);
        }
    }

    @Override
    protected void initFields()
    {
        mAdapterListViewBookList = new AdapterListViewBookList(this);
        mBusinessBook = new BusinessBook();
    }

    @Override
    protected void initViews()
    {
        mFramebodyBook_ListView_BookList = (ListView) this.findViewById(R.id.FramebodyBook_ListView_BookList);
    }

    @Override
    protected void initListeners()
    {
        mFramebodyBook_ListView_BookList.setOnItemClickListener(this);
        mFramebodyBook_ListView_BookList.setEmptyView(findViewById(R.id.FramebodyBook_LinearLayout_Empty));
    }

    @Override
    protected void bindData()
    {
        mFramebodyBook_ListView_BookList.setAdapter(mAdapterListViewBookList);
    }

    @Override
    protected void register()
    {
        registerForContextMenu(mFramebodyBook_ListView_BookList);
    }
    
    
    @Override
    protected Object doInBackground(Object... params)
    {
        initFields();
        return null;
    }

    @Override
    protected void onPostExecute(Object result)
    {
        super.onPostExecute(result);
        initViews();
        initListeners();
        bindData();
        register();
    }

}

